// const router = require('koa-router')()
// const svgCaptcha = require('svg-captcha')
// const formidable = require("formidable")
// const fs = require("fs")
// const path = require("path");
// const jwt = require("jsonwebtoken");
// const myKey = "214ii"
// router.post("/login", async (ctx, next) => {
//   console.log("后端上传图片")
//   // console.log(ctx.req);
//   const form = new formidable.IncomingForm({
//     multiples: true,
//     uploadDir: path.join(__dirname, '../img'),
//     keepExtensions: true
//   })
//   console.log(form)
//   console.log(path.join(__dirname, '../upload/images'));//koaserver/upload
//   form.parse(ctx.req, async (err, fields, files) => {
//     console.log("新闻")
//     if (err) {
//       console.log(err);
//     }
//   })
//   ctx.body = "上传图片"


// })
// // router.post("/login", async (ctx, next) => {
// //   console.log("login")
// //   // console.log(ctx.req)
// //   let form = formidable(
// //     {
// //       uploadDir: path.join(__dirname, "../public/images"),
// //       keepExtensions: true,
// //       multiples: true
// //     }
// //   )
// //   console.log(form)
// //   form.parse(ctx.req, function (err, fields, files) {
// //     console.log("解析")
// //     if (err) {
// //       console.log(err);
// //     }
// //     let filePath = path.join(__dirname, "../public/images");
// //     fs.readdirSync(filePath)

// //   })
// //   ctx.body = "上传成功"
// // })

// router.get('/home', async (ctx, next) => {
//   const svg = svgCaptcha.create({
//     height: 40,
//     width: 160,
//     size: 4,
//     color: "blue",
//     noise: 2,
//   })

//   let img = svg.data;
//   ctx.response.type = 'image/svg+xml';
//   ctx.body = img;
//   text = svg.text;
//   console.log(text)

// })
// router.post("/check", async (ctx, next) => {
//   if (!ctx.header.authorization) {
//     console.log("没有")
//     return
//   }
//   if (!ctx.header.authorization || ctx.header.authorization.length < 1) {
//     console.log("错误")
//     return false
//   }
//   try {
//     let userData = jwt.verify(ctx.header.authorization, myKey);
//     console.log("token有效")
//     ctx.body = "token有效"

//     return userData

//   } catch (err) {
//     return false;
//   }


// })
// router.post('/yanzheng', async (ctx, next) => {
//   const dirpath = path.join(__dirname, '/user.json')
//   console.log("路径" + dirpath);
//   const data = JSON.parse((fs.readFileSync(path.join(__dirname, '/user.json'))).toString());
//   console.log(data)
//   let username = ctx.request.body.username;
//   let pwd = ctx.request.body.pwd;
//   let imgCode = ctx.request.body.imgCode;
//   console.log(username, pwd, imgCode);
//   for (let i = 0; i < data.length; i++) {
//     if (username == data[i].username && pwd == data[i].pwd && imgCode == text) {
//       let token = jwt.sign({ username: ctx.request.body.username }, myKey);

//       ctx.body = { "code": 200, "msg": "success", "token": token }
//     } else {
//       ctx.body = { "code": 500, "msg": "fail" }
//     }

//   }
// })






// // let chapterList = [{
// //   chapterId: 1,
// //   chapterTitle: '学习',
// //   chapterTime: '2023-3-3'
// // },
// // {
// //   chapterId: 2,
// //   chapterTitle: '努力',
// //   chapterTime: '2023-3-3'
// // },
// // {
// //   chapterId: 3,
// //   chapterTitle: '运气',
// //   chapterTime: '2023-3-3'
// // }
// // ];

// // router.get('/', async (ctx, next) => {
// //   await ctx.render('index', {
// //     title: 'Hello Koa 2!'
// //   })
// // })
// // router.post("/subform", async (ctx, next) => {
// //   let chapterTitle = ctx.request.body.chapterTitle;
// //   let chapterTime = ctx.request.body.chapterTime;
// //   let dateObj = new Date(chapterTime);
// //   chapterTime = dateObj.getFullYear() + "-" + (dateObj.getMonth() + 1) + "-" + dateObj.getDate();
// //   let chapter = {
// //     chapterId: Math.random(),
// //     chapterTitle: chapterTitle,
// //     chapterTime: chapterTime
// //   }
// //   chapterList.push(chapter)
// //   ctx.body = { "code": 200, "msg": "success" }
// //   console.log(chapterTitle, chapterTime)
// // })

// // //后端
// // router.get("/getdata", async (ctx, next) => {
// //   console.log("receivie request");
// //   ctx.body = "receivie data"

// // })

// // router.get("/getlist", async (ctx, next) => {
// //   console.log(ctx);
// //   ctx.body = chapterList;
// // })
// // router.post("/sub", async (ctx, next) => {
// //   let chapter = {
// //     chapterId: Math.random(),
// //     chapterTitle: ctx.request.body.chapterTitle,
// //     chapterTime: ctx.request.body.chapterTime
// //   }
// //   chapterList.push(chapter);
// //   //传到后端
// //   console.log(ctx.request.body);
// //   //传到前端
// //   ctx.body = { chapterId: chapter.chapterId, status: "ok" }  //传一个对象
// //   // ctx.body = "ok";
// // })
// // router.post("/del", async (ctx, next) => {
// //   console.log(ctx.request.body.id);
// //   let index = '';
// //   let list = chapterList.filter((val) => val.chapterId !== ctx.request.body.id);
// //   console.log(list);
// //   //传到前端
// //   ctx.body = "success";

// // })
// // router.get('/string', async (ctx, next) => {
// //   ctx.body = 'koa2 string'
// // })

// // router.get('/json', async (ctx, next) => {
// //   ctx.body = {
// //     title: 'koa2 json'
// //   }
// // })
// // router.post("/ed", async (ctx, next) => {
// //   console.log("后端修改")
// //   let chapterId = ctx.request.body.chapterId;
// //   let chapterTitle = ctx.request.body.chapterTitle;
// //   let chapterTime = ctx.request.body.chapterTime;
// //   console.log(chapterId)
// //   for (let i = 0; i < chapterList.length; i++) {
// //     if (chapterList[i].chapterId == chapterId) {
// //       console.log("条件")
// //       chapterList[i].chapterTitle = chapterTitle;
// //       chapterList[i].chapterTime = chapterTime;
// //       ctx.body = { "msg": "ok", "code": 200 }
// //       break;
// //     }
// //   }
// // })



// module.exports = router
// const router = require('koa-router')()
const svgCaptcha = require('svg-captcha')
const fs = require("fs")
const jwt = require("jsonwebtoken");
const myKey = "214ii"
const router = require('koa-router')()
const formidable = require('formidable');
const path = require("path")
router.post("/login", async (ctx, next) => {
  console.log(ctx.req)
  const form = formidable({
    multiples: true,
    uploadDir: __dirname,
    keepExtensions: true
  });
  form.parse(ctx.req, async (err, fields, files) => {
    console.log("解析")
    if (err) {
      console.log(err)
    }
    console.log(fields);
    console.log(files);
  })
  ctx.body = "上传成功"
})

// router.post("/login", async (ctx, next) => {
//   console.log("后端上传图片")
//   ctx.body = "上传图片"






// })
router.get('/home', async (ctx, next) => {
  const svg = svgCaptcha.create({
    height: 40,
    width: 160,
    size: 4,
    color: "blue",
    noise: 2,
  })

  let img = svg.data;
  ctx.response.type = 'image/svg+xml';
  ctx.body = img;
  text = svg.text;
  console.log(text)

})
router.post("/check", async (ctx, next) => {
  if (!ctx.header.authorization) {
    console.log("没有")
    return
  }
  if (!ctx.header.authorization || ctx.header.authorization.length < 1) {
    console.log("错误")
    return false
  }
  try {
    let userData = jwt.verify(ctx.header.authorization, myKey);
    console.log("token有效")
    ctx.body = "token有效"

    return userData

  } catch (err) {
    return false;
  }


})
router.post("/upload", async (ctx, next) => {
  console.log(ctx.request.body.list)
  let sql = `insert into image(name, size, url, src,only)` + `values(?,?,?,?,?)`
  for (let i = 0; i < ctx.request.body.list.length; i++) {
    let name = ctx.request.body.list[i].name;
    let size = ctx.request.body.list[i].size;
    let url = ctx.request.body.list[i].url;
    let src = ctx.request.body.list[i].src;
    let only = ctx.request.body.list[i].only;
    let res = await ctx.db.EXCUTE(sql, [name, size, url, src, only]);
    console.log(res)
    ctx.body = "上传成功"
  }
  ctx.body = "上传成功了吗"
})
router.get("/imageList", async (ctx, next) => {
  console.log(ctx.request.body)
  let sql = "select * from image";
  let result = await ctx.db.EXCUTE(sql);
  console.log("结果：")
  console.log(result)
  ctx.body = result;
})
router.post('/yanzheng', async (ctx, next) => {
  let sql = "select * from login";
  let result = await ctx.db.EXCUTE(sql);
  console.log("结果：")
  console.log(result[0])
  let data = result[0];
  // const dirpath = path.join(__dirname, '/user.json')
  // console.log("路径" + dirpath);
  // const data = JSON.parse((fs.readFileSync(path.join(__dirname, '/user.json'))).toString());
  // console.log(data)
  let username = ctx.request.body.username;
  let pwd = ctx.request.body.pwd;
  let imgCode = ctx.request.body.imgCode;
  console.log(username, pwd, imgCode);
  for (let i = 0; i < result.length; i++) {
    if (username == result[i].username && pwd == result[i].pwd && imgCode == text) {
      let token = jwt.sign({ username: ctx.request.body.username }, myKey);

      ctx.body = { "code": 200, "msg": "success", "token": token }
    } else {
      ctx.body = { "code": 500, "msg": "fail" }
    }

  }
})
router.get('/list', async (ctx, next) => {
  // const dirpath = path.join(__dirname, '/user2.json');
  // console.log(dirpath)
  // const data = JSON.parse((fs.readFileSync(path.join(__dirname, '/user2.json'))).toString());
  // console.log(data);
  // ctx.body = data;
  let sql = "select * from users";
  let result = await ctx.db.EXCUTE(sql);
  console.log("结果：")
  console.log(result)
  ctx.body = result;
})
router.get('/list2', async (ctx, next) => {
  // let sql = "select * from root";
  let sql = "select * from root order by top desc,time desc"
  let result = await ctx.db.EXCUTE(sql, [1]);
  console.log("结果：")
  console.log(result[0])
  ctx.body = result;
})
router.post("/change", async (ctx, next) => {
  console.log(ctx.request.body)
  let newusername = ctx.request.body.newusername;
  let newnumber = ctx.request.body.newnumber;
  let newemail = ctx.request.body.newemail;
  let newaddress = ctx.request.body.newaddress;
  let username = ctx.request.body.username;
  let number = ctx.request.body.number;
  let email = ctx.request.body.email;
  let address = ctx.request.body.address;
  let only = ctx.request.body.only;
  let sql = "update users set username=?,number=?, email=?, address=? where username=? and number=? and email=? and address=? and only=?"
  let res = await ctx.db.EXCUTE(sql, [newusername, newnumber, newemail, newaddress, username, number, email, address, only]);
  console.log(res)
  ctx.body = "修改成功"
})
router.post("/change2", async (ctx, next) => {
  console.log(ctx.request.body)
  let newname = ctx.request.body.newname;
  let newtujing = ctx.request.body.newtujing;
  let newaddress = ctx.request.body.newaddress;
  let newnum = ctx.request.body.newnum;
  let name = ctx.request.body.name;
  let tujing = ctx.request.body.tujing;
  let address = ctx.request.body.address;
  let only = ctx.request.body.only;
  let num = ctx.request.body.num;
  let sql = "update root set name=?,tujing=?, address=?, num=? where name=? and tujing=? and address=? and num=? and only=?"
  let res = await ctx.db.EXCUTE(sql, [newname, newtujing, newaddress, newnum, name, tujing, address, num, only]);
  console.log(res)
  ctx.body = "修改成功"
})
router.post("/add", async (ctx, next) => {
  console.log(ctx.request.body);
  let username = ctx.request.body.username;
  let number = ctx.request.body.number;
  let email = ctx.request.body.email;
  let address = ctx.request.body.address;
  let only = ctx.request.body.only;

  let sql = `insert into users(username, number, email, address,only)` + `values(?,?,?,?,?)`
  let res = await ctx.db.EXCUTE(sql, [username, number, email, address, only]);
  let sql2 = "select * from users";
  let result = await ctx.db.EXCUTE(sql2);
  console.log(res)
  ctx.body = result;
})
router.post("/add2", async (ctx, next) => {
  console.log(ctx.request.body);
  let name = ctx.request.body.name;
  let tujing = ctx.request.body.tujing;
  let address = ctx.request.body.address;
  let num = ctx.request.body.num;
  let only = ctx.request.body.only;
  let top = ctx.request.body.top;
  let sql = `insert into root(name, tujing, address, num,only,top)` + `values(?,?,?,?,?,?)`
  let res = await ctx.db.EXCUTE(sql, [name, tujing, address, num, only, top]);
  let sql2 = "select * from root";
  let result = await ctx.db.EXCUTE(sql2);
  console.log(res)
  ctx.body = result;
})
router.post("/del", async (ctx, next) => {
  console.log(ctx.request.body);
  let username = ctx.request.body.username;
  let number = ctx.request.body.number;
  let email = ctx.request.body.email;
  let address = ctx.request.body.address;
  let only = ctx.request.body.only;
  console.log(username, number, email, address)
  let sql = "delete from users where username=? and number=? and email=? and address=? and only=?"
  let res = await ctx.db.EXCUTE(sql, [username, number, email, address, only]);
  console.log(res)
  ctx.body = "删除成功"
})
router.post("/del2", async (ctx, next) => {
  console.log(ctx.request.body);
  let name = ctx.request.body.name;
  let tujing = ctx.request.body.tujing;
  let address = ctx.request.body.address;
  let num = ctx.request.body.num;
  let only = ctx.request.body.only;
  let sql = "delete from root where name=? and tujing=? and address=? and num=? and only=?"
  let res = await ctx.db.EXCUTE(sql, [name, tujing, address, num, only]);
  console.log(res)
  ctx.body = "删除成功"
})
router.post("/del3", async (ctx, next) => {
  console.log(ctx.request.body);
  let name = ctx.request.body.name;
  let size = ctx.request.body.size;
  let url = ctx.request.body.url;
  let src = ctx.request.body.src;
  let only = ctx.request.body.only;
  let sql = "delete from image where name=? and size=? and url=? and src=? and only=?"
  let res = await ctx.db.EXCUTE(sql, [name, size, url, src, only]);
  console.log(res)
  ctx.body = "删除成功"
})
router.post("/search", async (ctx, next) => {
  console.log("搜索功能")
  console.log(ctx.request.body);
  let sea = ctx.request.body.sea;
  let sql = "select * from root  where name=? or tujing=? or address=? or num=?";
  let result = await ctx.db.EXCUTE(sql, [sea, sea, sea, sea]);
  console.log("结果：")
  console.log(result)
  ctx.body = result;
})
router.post("/zhiding", async (ctx, next) => {
  console.log("置顶功能")
  let only = ctx.request.body.only;
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var Hours = date.getHours();
  var Minutes = date.getMinutes();
  var Seconds = date.getSeconds();
  if (month < 10) {
    month = "0" + month;
  }
  if (day < 10) {
    day = "0" + day;
  }
  var time = year + '-' + month + '-' + day + ' ' + Hours + ':' + Minutes + ':' + Seconds;
  console.log(time, only);
  let top = 1;
  let sql2 = "update root set time=?, top=? where only =?"
  let result = await ctx.db.EXCUTE(sql2, [time, top, only]);
  ctx.body = result;
})
module.exports = router
